<template>
  <div>
    <Category></Category>
    <el-card style="margin: 0px 15px">
      <template class="attrInfo" v-if="attrInfoVisible">
        <el-button
          type="primary"
          icon="Plus"
          @click="addAttr"
          :disabled="!categoryStore.c3Id"
          >添加平台属性</el-button
        >
        <el-table border style="width: 100%; margin: 15px 0" :data="attrData">
          <el-table-column prop="id" label="序号" width="120" align="center" />
          <el-table-column prop="attrName" label="属性名称" align="center" />
          <el-table-column label="属性值名称" align="center">
            <template #="{ row }">
              <!-- {{ row }} -->
              <el-tag
                :type="getTagType()"
                v-for="attr in row.attrValueList"
                style="margin-right: 7px"
                >{{ attr.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #="{ row, $index }">
              <el-button
                icon="Edit"
                size="small"
                type="warning"
                @click="updateAttr(row)"
              ></el-button>
              <el-button
                icon="Delete"
                size="small"
                type="danger"
                @click="deleteAttr(row.id)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template v-else>
        <el-form :model="attrValueInfo" :rules="rules" ref="attrInfoRef">
          <el-form-item label="属性名称" prop="attrName">
            <el-input
              style="width: 150px"
              size="small"
              v-model="attrValueInfo.attrName"
            ></el-input>
          </el-form-item>
          <div>
            <el-button
              type="primary"
              icon="Plus"
              @click="addAttrValue"
              :disabled="!canAddAttrValue || !canAddAttrValue2"
              >添加属性值</el-button
            >
            <el-button
              :disabled="!canCancelAttrValue"
              @click="cancelAddAttrValue"
              >取消</el-button
            >
          </div>
          <el-form-item prop="attrValueList">
            <el-table
              border
              style="width: 100%; margin-top: 15px"
              :data="attrValueInfo.attrValueList"
            >
              <el-table-column
                type="index"
                label="序号"
                width="120"
                align="center"
              />
              <el-table-column label="属性值" align="center">
                <template #="{ row, $index }">
                  <el-input
                    :ref="(vc:any)=>inputArr[$index]=vc"
                    v-model="row.valueName"
                    v-if="row.flag"
                    @blur="toLook(row)"
                  ></el-input>
                  <div v-else @click="toEdit(row, $index)">
                    {{ row.valueName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template #="{ row, $index }">
                  <el-button
                    icon="Delete"
                    size="small"
                    type="danger"
                    :disabled="row.flag"
                    @click="deleteAttrValue($index)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <div>
            <el-button type="primary" @click="saveAttrInfo">保存</el-button>
            <el-button @click="cancelEditAttrInfo">取消</el-button>
          </div>
        </el-form>
      </template>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, reactive, toRaw, nextTick, onBeforeUnmount } from "vue";
import { ElLoading } from "element-plus";
import useCategoryStore from "../../../store/modules/category";
import {
  reqAttrInfo,
  reqDelAttrInfo,
  reqSaveAttrInfo,
} from "../../../api/product/attr";
import { ElMessage } from "element-plus";
import confirm from "../../../utils/confirm";
import component from "element-plus/es/components/tree-select/src/tree-select-option.mjs";
const categoryStore = useCategoryStore();
const attrData = ref();
const canAddAttrValue = ref(true);
const canAddAttrValue2 = ref(true);
const canCancelAttrValue = ref(false);
const attrInfoRef = ref();
const inputArr = ref<any>([]);
let attrValueInfo = reactive<any>({ attrName: "", attrValueList: [] });
const attrInfoVisible = ref(true);
const rules = {
  attrName: [{ required: true, min: 2, max: 10, trigger: "blur" }],
  attrValueList: [{ required: true, trigger: "blur" }],
};
// 上面的三个分类是否禁用
watch(attrInfoVisible, (value) => {
  categoryStore.isDisabled = !value;
});
// 确保能够再次添加attrValue
watch(
  () => attrValueInfo.attrValueList,
  () => {
    let length = attrValueInfo.attrValueList.length;
    if (length > 0) {
      // console.log(attrValueInfo.attrValueList[length - 1].valueName.length);
      canAddAttrValue.value =
        attrValueInfo.attrValueList[length - 1].valueName.length > 0
          ? true
          : false;
      canCancelAttrValue.value =
        attrValueInfo.attrValueList[length - 1].valueName.length > 0
          ? false
          : true;
    } else {
      canCancelAttrValue.value = false;
      canAddAttrValue.value = true;
    }
  },
  { deep: true }
);
watch(
  () => categoryStore.c3Id,
  async () => {
    // console.log(categoryStore.c3Id !== "");
    if (categoryStore.c3Id !== "") {
      let result = await reqAttrInfo(
        categoryStore.c1Id as number,
        categoryStore.c2Id as number,
        categoryStore.c3Id as number
      );
      attrData.value = result.data;
      attrValueInfo.categoryId = categoryStore.c3Id;
      attrValueInfo.categoryLevel = 3;
      // console.log(attrData.value);
    } else {
      attrData.value = null;
    }
  }
);
let loadingInstance: any;

const startLoading = () => {
  loadingInstance = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
};
const endLoading = () => {
  loadingInstance.close();
};
const tagType = ["primary", "success"];
const getTagType = () => {
  return tagType[Math.round(Math.random())];
};
// 编辑属性
const updateAttr = (data: any) => {
  attrInfoVisible.value = false;
  // attrValueInfo = reactive({ ...toRaw(data) });
  Object.assign(attrValueInfo, JSON.parse(JSON.stringify(data)));
  console.log(attrValueInfo);
};
// 删除属性
const deleteAttr = (id: number) => {
  console.log(id);
  confirm("你确定要删除该属性吗？", async () => {
    startLoading();
    try {
      reqDelAttrInfo(id);
    } catch (error: any) {
      ElMessage.error(error.message);
    } finally {
      // nextTick(async () => {
      //   let result = await reqAttrInfo(
      //     categoryStore.c1Id as number,
      //     categoryStore.c2Id as number,
      //     categoryStore.c3Id as number
      //   );
      //   attrData.value = result.data;
      //   console.log(result.data);
      //   endLoading();
      //   ElMessage.success("删除成功");
      // });
      setTimeout(async () => {
        let result = await reqAttrInfo(
          categoryStore.c1Id as number,
          categoryStore.c2Id as number,
          categoryStore.c3Id as number
        );
        attrData.value = result.data;
        console.log(result.data);
        endLoading();
        ElMessage.success("删除成功");
      }, 3000);
    }
  });
};
// 添加属性
const addAttr = () => {
  attrInfoVisible.value = false;
  Object.assign(attrValueInfo, { attrName: "", attrValueList: [], id: "" });
  console.log(attrValueInfo);
};

// 添加属性值:最小分支
const addAttrValue = () => {
  attrValueInfo.attrValueList.push({ valueName: "", flag: true });
  nextTick(() => {
    let length = attrValueInfo.attrValueList.length;
    inputArr.value[length - 1].focus();
  });
};
// 删除属性值：最小分支
const deleteAttrValue = (index: number) => {
  attrValueInfo.attrValueList.splice(index, 1);
};

// 提交添加/删除属性值的请求
const saveAttrInfo = async () => {
  // attrInfoVisible.value = true;
  // console.log(attrValueInfo);
  startLoading();
  attrInfoRef.value.validate(async (valid: any) => {
    if (!valid) {
      endLoading();
      return;
    }
    let result = await reqSaveAttrInfo(attrValueInfo);
    endLoading();
    if (result.code === 200) {
      // 重新从服务器取属性数据
      startLoading();
      let result = await reqAttrInfo(
        categoryStore.c1Id as number,
        categoryStore.c2Id as number,
        categoryStore.c3Id as number
      );
      endLoading();
      attrData.value = result.data;
      attrInfoVisible.value = true;
    } else {
      ElMessage.error("操作失败");
    }
  });

  // console.log(result);
};
// 取消提交
const cancelEditAttrInfo = () => {
  attrInfoVisible.value = true;
};

const cancelAddAttrValue = () => {
  let length = attrValueInfo.attrValueList.length;
  attrValueInfo.attrValueList.splice(length - 1, 1);
  canAddAttrValue2.value = true;
};

const toLook = (data: any) => {
  // 内容为空,NO
  if (data.valueName.trim() === "") {
    ElMessage.error("属性值不能为空");
    canAddAttrValue2.value = false;
    return;
  }
  // 内容重复,NO
  let repeat = attrValueInfo.attrValueList.some((attrValue: any) => {
    if (attrValue != data)
      return attrValue.valueName.trim() === data.valueName.trim();
  });
  if (repeat) {
    ElMessage.error("属性值不能重复");
    canAddAttrValue2.value = false;
    return;
  }
  canAddAttrValue2.value = true;
  data.flag = false;
};
const toEdit = (data: any, $index: number) => {
  data.flag = true;
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};
// 切换组件时，清空数据
onBeforeUnmount(() => {
  categoryStore.$reset();
});
</script>

<style lang="scss" scoped></style>
